<template>
  <div class="com-container">
    <div class="com-chart" ref="rank_ref"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      chartInstance: null,
      allData: null,
      startValue: 0, // 区域缩放起点值
      endValue: 9, // 区域缩放起点值
      timeId: null // 定时器编号
    }
  },
  created () { // 组件创建后 - 函数
    // 组件创建时，注册socket的回调函数
    this.$socket.registerCallBack('rankData', this.getData)
  },
  mounted () {
    this.initChart()
    // this.getData()
    // 发送数据给服务器，告诉服务器，这个客户端需要数据
    this.$socket.send({
      action: 'getData',
      socketType: 'rankData',
      chartName: 'rank',
      value: ''
    })
    this.resizeChart()
    window.addEventListener('resize', this.resizeChart)
  },
  destoryed () {
    // 移除监听
    window.removeEventListener('resize', this.resizeChart)
    // 移除定时器
    this.removeInterval()
    // 组件销毁时，注销socket的回调函数
    this.$socket.unregisterCallBack('rankData')
  },
  methods: {
    // 1.初始化echarts对象
    initChart () {
      this.chartInstance = this.$echarts.init(this.$refs.rank_ref, this.theme)
      const initOption = {
        title: {
          text: '▎地区销售排行',
          textStyle: {
            fontSize: 36
          },
          left: 20,
          top: 20
        },
        grid: {
          top: '40%',
          bottom: '5%',
          left: '5%',
          right: '5%',
          containLabel: true
        },
        tooltip: {
          show: true
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value',
          name: '个/月'
        },
        series: {
          type: 'bar'
        }
      }
      this.chartInstance.setOption(initOption)
      this.chartInstance.on('mouseover', () => {
        clearInterval(this.timeId)
      })
      this.chartInstance.on('mouseout', () => {
        this.startInterval()
      })
    },

    // 2.获取地图数据
    getData (res) {
      // 获取数据
      // const { data: res } = await this.$http.get('rank')
      this.allData = res
      // 将allData降幂排序
      this.allData.sort((a, b) => {
        return b.value - a.value
      })
      this.updateChart()
      this.startInterval()
    },

    // 3.更新数据
    updateChart () {
      const colorArr = [
        ['#0BA82C', '#4FF778'],
        ['#2E72BF', '#23E5E5'],
        ['#5052EE', '#AB6EE5']
      ]
      // 处理图表需要的数据
      const xAxisArr = this.allData.map(item => {
        return item.name
      })
      const seriesArr = this.allData.map(item => {
        return item.value
      })
      const dataOption = {
        xAxis: {
          data: xAxisArr
        },
        dataZoom: { // 区域缩放
          show: false,
          startValue: this.startValue,
          endValue: this.endValue
        },
        series: {
          itemStyle: {
            color: (arg) => {
              let targetColorArr = null
              if (arg.value > 300) {
                targetColorArr = colorArr[0]
              } else if (arg.value > 200) {
                targetColorArr = colorArr[1]
              } else {
                targetColorArr = colorArr[2]
              }
              return new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: targetColorArr[0]
                },
                {
                  offset: 1,
                  color: targetColorArr[1]
                }
              ])
            }
          },
          data: seriesArr
        }
      }
      this.chartInstance.setOption(dataOption)
    },

    // 4.分辨率适配
    resizeChart () {
      const titleFontSize = this.$refs.rank_ref.offsetWidth / 100 * 3.6
      const resizeOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        series: [{
          barWidth: titleFontSize,
          itemStyle: {
            barBorderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0]
          }
        }]
      }
      this.chartInstance.setOption(resizeOption)
      this.chartInstance.resize()
    },

    // 5.定时改变区域缩放范围
    startInterval () {
      if (this.timeId) {
        this.removeInterval()
      }
      this.timeId = setInterval(() => {
        this.startValue++
        this.endValue++
        if (this.endValue > this.allData.length - 1) {
          this.startValue = 0
          this.endValue = 9
        }
        this.updateChart()
      }, 2000)
    },

    // 6.清除定时器
    removeInterval () {
      clearInterval(this.timeId)
    }
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme () {
      console.log('主题切换了')
      // 1.销毁当前图表
      this.chartInstance.dispose()
      // 2.重新注册当前图表 -- 以最新主题渲染图表
      this.initChart()
      this.resizeChart()
      this.updateChart()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
